package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.QUserRole;
import com.xinhe.web.entity.QYunChaSeedAssetCount;
import com.xinhe.web.entity.UserRole;
import com.xinhe.web.entity.YunChaSeedAssetCount;
import com.xinhe.web.reposity.UserRoleRepository;
import com.xinhe.web.util.Snowflake;
import com.xinhe.web.vo.UserRoleModel;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserRoleService {
    //初始化查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }
    @Autowired
    UserRoleRepository userRoleRepository;

    @Transactional
    public Result saveUserRole(UserRoleModel model) {
        List<UserRole> userRoles = userRoleRepository.findByUserId(model.getUserId());
        Map<Long, UserRole> userRoleMap = new HashMap<>();
        for (UserRole userRole : userRoles) {
            userRoleMap.put(userRole.getRoleId(), userRole);
        }
        this.userRoleRepository.deleteByUserId(model.getUserId());
        if (CollectionUtils.isNotEmpty(model.getRoleIds())) {
            for (Long roleId : model.getRoleIds()) {
                UserRole userRole = userRoleMap.get(roleId);
                if (null == userRole) {
                    userRole = new UserRole();
                    userRole.setId(Snowflake.generateId());
                    userRole.setRoleId(roleId);
                    userRole.setUserId(model.getUserId());
                    userRoleRepository.save(userRole);
                    continue;
                }
                userRole.setRemoved(Integer.valueOf(0));
                userRoleRepository.saveAndFlush(userRole);
            }
        }
        return Result.ok();
    }


    public QueryResults<UserRole> pageUserRole(Long userId, Long roleId, int pageNum, int pageSize) {
        QUserRole qUserRole = QUserRole.userRole;
        BooleanBuilder builder = new BooleanBuilder();
        //builder.and(qTeamBuy.removed.eq(0));
        if (!Objects.isNull(userId)) {
            builder.and(qUserRole.userId.eq(userId));
        }
        if (!Objects.isNull(roleId)) {
            builder.and(qUserRole.roleId.eq(roleId));
        }
        return queryFactory.select(
                        Projections.bean(
                                UserRole.class,
                                qUserRole.id,
                                qUserRole.userId,
                                qUserRole.roleId,
                                qUserRole.createTime
                        )
                ).from(qUserRole)
                .offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }


    public Result findById(Long userRoleId) {
        return Result.ok(userRoleRepository.findById(userRoleId).get());
    }

    public Result delete(Long userRoleId) {
        userRoleRepository.deleteById(userRoleId);
        return Result.ok();
    }
}
